﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinKeyBoard.Helpers;
using WinKeyBoard.UcControls;
using static WinKeyBoard.UcControls.UcNumKey;

namespace WinKeyBoard.Pages
{
    public partial class FrmNum : UIForm
    {
        public FrmNum()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 定义计时次数
        /// </summary>
        int timerIndex = 0;

        #region 设置为浮动窗体，不获取焦点，用了之后，鼠标悬停控件不会显示Tip
        private const int WS_EX_TOOLWINDOW = 0x00000080;
        private const int WS_DISABLED = 0x08000000;//窗口最初处于禁用状态。 已禁用的窗口无法接收用户的输入。 若要在创建窗口后更改此设置，请使用 EnableWindow 函数
        private const int WS_EX_TOPMOST = 0x00000008;//是否置顶
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle = (WS_DISABLED | WS_EX_TOOLWINDOW | WS_EX_TOPMOST);
                //cp.Parent = IntPtr.Zero; // Keep this line only if you used UserControl
                //cp.X = this.Location.X;
                //cp.Y = this.Location.Y;
                return cp;

                //return base.CreateParams;
            }
        }

        #endregion

        /// <summary>
        /// 没实现
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.Space))
            {
                // 根据你的需求创建并显示弹出窗体
                //this.Show();
                MessageBox.Show($"123");
                return true; // 返回 true 表示已处理按键事件
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        /// <summary>
        /// 当前页面模块
        /// </summary>
        private static UIUserControl CurrentUC;

        //初始化
        private void FrmKeyboard_Load(object sender, EventArgs e)
        {
            SetPosition();

            InitSettings();

            //ucShortcutKey1.showInputTextDelegate = this.ShowInputText;//快捷键
            ucControlKey1.showInputTextDelegate = this.ShowInputText;//控制区
            ucNumKey1.showInputTextDelegate = this.ShowInputText;//数字区
            ucNumKey1.conStateDelegate = this.ShowControlKey;
            ShowControlKey(LightState.Close);

        }
        //窗口关闭
        private void FrmNum_FormClosed(object sender, FormClosedEventArgs e)
        {
            niLogo.Visible = false;
        }
        /// <summary>
        /// 初始化设置
        /// </summary>
        public void InitSettings()
        {
            #region 主题
            //主题
            string argb = "80, 160, 255";
            var theme = IniHelper.ReadOrWrite(Sections.Theme, argb.Replace(" ", ""), "主题");

            string[] a = theme.Split(',');

            Color color = Color.FromArgb(Convert.ToInt32(a[0]), Convert.ToInt32(a[1]), Convert.ToInt32(a[2]));
            UIStyles.InitColorful(color, Color.White);
            #endregion


            //开机自启动
            IniHelper.ReadOrWrite(Sections.AutoStart, "0", "开机时，是否自动启动");


            #region 启动后是否停靠边缘
            //启动后是否停靠边缘
            string startDockStr = IniHelper.ReadOrWrite(Sections.StartDock, "0", "启动后，是否自动靠边隐藏窗体");
            bool isStartDock = startDockStr == "0" ? false : true;
            if (isStartDock)
            {
                SetPosition(0);
            }
            #endregion

            IniHelper.ReadOrWrite(Sections.Minimized, "0", "窗口关闭时，是否最小化到系统托盘");

            IniHelper.ReadOrWrite(Sections.CloseWarn, "0", "下次关闭时，是否不再提醒我");

            string hideHead = IniHelper.ReadOrWrite(Sections.HideHeader, "0", "是否隐藏头部");
            chkHideHeader.Checked = hideHead == "0" ? false : true;
        }

        #region 右上角的按钮
        //关闭
        private void btnClose_Click(object sender, EventArgs e)
        {
            string CloseWarn = IniHelper.ReadValue(Sections.CloseWarn);
            string Minimized = IniHelper.ReadValue(Sections.Minimized);

            if (CloseWarn == "0")
            {
                //弹框提示设置
                FrmCloseWarn frm = new FrmCloseWarn();
                frm.TopMost = true;
                frm.ShowDialog();
            }
            else if (Minimized == "1")
            {
                //隐藏（最小化到系统托盘）
                FormHelper.ShowWindow(this.Handle, 2);
            }
            else
            {
                //正常退出程序
                Application.Exit();
            }
            
        }
        //隐藏
        private void btnHide_Click(object sender, EventArgs e)
        {
            FormHelper.ShowWindow(this.Handle, 2);
        }
        //设置
        private void btnSettings_Click(object sender, EventArgs e)
        {
            ShowFrmSettings();
        }
        #endregion

        #region 退格按钮
        //鼠标按下
        private void btnBackSpace_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ShowInputText();
                timerIndex = 1;
                SendKeys.Send("{BACKSPACE}");
                // 启动一个计时器，用于重复执行你的操作
                timerBackSpace.Interval = 100;
                timerBackSpace.Start();
            }
        }
        //计时器
        private void timerBackSpace_Tick(object sender, EventArgs e)
        {
            #region 退格事件
            timerIndex++;
            if (timerIndex >= 3)
            {
                timerBackSpace.Interval = 10;
            }
            else if (timerIndex > 10)
            {
                timerBackSpace.Interval = 1;
                SendKeys.Send("{BACKSPACE}");
            }

            SendKeys.Send("{BACKSPACE}");
            #endregion
        }
        private void btnBackSpace_MouseUp(object sender, MouseEventArgs e)
        {
            // 停止计时器
            timerBackSpace.Stop();
        }
        #endregion
        
        #region 窗体移动事件
        private void uiHeader_MouseDown(object sender, MouseEventArgs e)
        {
            FormHelper.MoveWindow(this.Handle);
        }
        private void panelCenter_MouseDown(object sender, MouseEventArgs e)
        {
            FormHelper.MoveWindow(this.Handle);
        }

        private void panelBottom_MouseDown(object sender, MouseEventArgs e)
        {
            FormHelper.MoveWindow(this.Handle);
        }

        private void panelBody_MouseDown(object sender, MouseEventArgs e)
        {
            FormHelper.MoveWindow(this.Handle);
        }

        private void txtInput_MouseDown(object sender, MouseEventArgs e)
        {
            FormHelper.MoveWindow(this.Handle);
        }
        #endregion

        /// <summary>
        /// 显示设置界面窗体
        /// </summary>
        private void ShowFrmSettings()
        {
            FrmSettings frm = new FrmSettings();
            frm.TopMost = true;
            frm.Show();
        }

        #region 自动检测窗体隐藏
        private void timerDock_Tick(object sender, EventArgs e)
        {
            bool isDock = FormHelper.AutoSideHideOrShow(this, 5);
            if (isDock)
            {
                ShowInputText();//如果隐藏成功，清除文本框
            }
            
        }
        #endregion

        /// <summary>
        /// 设置窗体位置
        /// </summary>
        private void SetPosition(int num = 10)
        {
            //当前显示器的宽度
            int screenWidth = Screen.PrimaryScreen.WorkingArea.Size.Width;
            int screenHeight = Screen.PrimaryScreen.WorkingArea.Size.Height;

            int x = screenWidth - this.Size.Width - num;
            int y = screenHeight - this.Size.Height - num;
            this.SetDesktopLocation(x, y);//设置窗体打开后在显示器上的坐标
        }

        /// <summary>
        /// 显示输入的文本
        /// </summary>
        /// <param name="obj">文本</param>
        public void ShowInputText(object obj = null)
        {
            txtInput.Invoke(new Action(() => {
                if (obj == null)
                {
                    txtInput.Text = "";
                }
                else
                {
                    txtInput.AppendText($"{obj}");
                }
            }));
        }
        /// <summary>
        /// 显示键盘控制区的按钮
        /// </summary>
        /// <param name="state"></param>
        private void ShowControlKey(LightState state)
        {
            if (state == LightState.Open)
            {
                //两个区都显示
                uiPanel1.Visible = true;
                panelBody.Visible = true;

                // 调整窗体位置和大小
                this.Width += uiPanel1.Width;
                this.Left -= uiPanel1.Width;
            }
            else
            {
                //只显示panelBody
                uiPanel1.Visible = false;//左
                panelBody.Visible = true;//右

                // 调整窗体位置和大小：控件会从左到右靠拢，不写则将右边的控件全部从右到左靠拢
                this.Width -= uiPanel1.Width;
                this.Left += uiPanel1.Width;
            }
        }

        #region 隐藏头部
        private void chkHideHeader_CheckedChanged(object sender, EventArgs e)
        {
            string hideHead = chkHideHeader.Checked ? "1" : "0";
            IniHelper.WriteValue(Sections.HideHeader, hideHead);

            panelTop.Visible = !chkHideHeader.Checked;

            AdjustFormSize();
        }
        /// <summary>
        /// 调整窗体大小
        /// </summary>
        private void AdjustFormSize()
        {
            if (panelTop.Visible)
            {
                // 如果头部 panel 可见，则将窗体的顶部边界还原
                int headerHeight = panelTop.Height;
                int currentTop = this.Top;
                this.Top = currentTop - headerHeight;
                this.Height += headerHeight;
            }
            else
            {
                // 如果头部 panel 隐藏，则将窗体的顶部边界向上移动
                int headerHeight = panelTop.Height;
                int currentTop = this.Top;
                this.Top = currentTop + headerHeight;
                this.Height -= headerHeight;
            }
        }
        #endregion

        #region 任务栏图标事件
        //双击
        private void niLogo_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            FormHelper.ShowWindow(this.Handle, 1);
        }
        //显示主窗体
        private void tsmiShowForm_Click(object sender, EventArgs e)
        {
            FormHelper.ShowWindow(this.Handle, 1);
        }
        //设置
        private void tsmiSetting_Click(object sender, EventArgs e)
        {
            ShowFrmSettings();
        }
        //退出
        private void tsmiClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion

    }
}
